package com.zkx.fssb.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zkx.fssb.constant.PasswordConstant;
import com.zkx.fssb.domain.dto.UserDto;
import com.zkx.fssb.domain.po.User;
import com.zkx.fssb.domain.vo.UserVo;
import com.zkx.fssb.exception.AccountNotFoundException;
import com.zkx.fssb.exception.LoginFailedException;
import com.zkx.fssb.mapper.UserMapper;
import com.zkx.fssb.properties.JwtProperties;
import com.zkx.fssb.service.UserService;
import com.zkx.fssb.utils.JwtUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Autowired
    private JwtProperties jwtProperties;



    @Override
    public UserVo login(UserDto userDto) {
        LambdaQueryWrapper<User> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(User::getUserName,userDto.getUserName());
        User user = this.getBaseMapper().selectOne(lambdaQueryWrapper);
        if (user==null){
            throw new AccountNotFoundException("账号不存在");
        }
        if (!user.getPassword().equals(userDto.getPassword())){
            throw new LoginFailedException("用户名或密码错误");
        }

        UserVo userVo = new UserVo();
        BeanUtils.copyProperties(user,userVo);

//        User user = this.getById(1);
//        log.info("user,{}",user);




        Map<String,Object> map = new HashMap<>();
        map.put("userId",userVo.getUserId());
        String token = JwtUtil.createJWT(jwtProperties.getAdminSecretKey(), jwtProperties.getAdminTtl(), map);
        userVo.setToken(token);


        return userVo;

    }

    @Override
    public void register(UserDto userDto) {
        LambdaQueryWrapper<User> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(User::getUserName,userDto.getUserName());

        if (this.getBaseMapper().selectOne(lambdaQueryWrapper)!=null){
            throw new LoginFailedException("账号已存在,换一个试试");
        }

        User user = new User();
        BeanUtils.copyProperties(userDto,user);
        user.setPassword(PasswordConstant.DEFAULT_PASSWORD);
        this.save(user);




    }
}
